package com.xk.sport.backend.web.controller.api;

import com.xk.sport.backend.common.constant.Constants;
import com.xk.sport.backend.common.constant.ResultStatus;
import com.xk.sport.backend.common.entity.Result;
import com.xk.sport.backend.dao.model.Task;
import com.xk.sport.backend.dao.model.Teacher;
import com.xk.sport.backend.service.LessonService;
import com.xk.sport.backend.service.TaskService;
import com.xk.sport.backend.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping(value = "/api")
public class ApiController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private LessonService lessonService;
    @Autowired
    private TaskService taskService;

    /**
     * 获取还未开始的，还未被选中的任务
     *
     * @return
     */
    @RequestMapping("/validTasks")
    @ResponseBody
    public Result validTasks() {
        return new Result(ResultStatus.success.getStatus(), "", taskService.findValid());
    }

    /**
     * 获取还未开始的，还未被选中的任务
     *
     * @return
     */
    @RequestMapping("/validTaskByCode")
    @ResponseBody
    public Result validTaskByCode(String code) {
        Map<String, Object> data = new HashMap<>();
        data.put("tasks", taskService.findValidByTeacher(code));
        data.put("teacher", teacherService.findOneByCode(code));
        return new Result(ResultStatus.success.getStatus(), "", data);
    }

    /**
     * 指定教师选择指定课程
     *
     * @param code   教师code
     * @param taskId 任务id
     * @return
     */
    @RequestMapping("/selectTask")
    @ResponseBody
    public Result selectTask(String code, long taskId) {
        Teacher teacher = teacherService.findOneByCode(code);
        if (teacher == null) {
            return new Result(ResultStatus.normal_error.getStatus(), "您输入的教师编码有误");
        }
        Task task = taskService.findOne(taskId);
        if (task == null || task.getTeacherId() > 0) {
            return new Result(ResultStatus.normal_error.getStatus(), "此课程已被点选");
        }
        Set<Long> lessonIds = teacherService.findLessonIds(teacher.getId());
        if (!lessonIds.contains(task.getLessonId())) {
            return new Result(ResultStatus.normal_error.getStatus(), "您不是此课程注册教师");
        }
        taskService.selectTask(teacher.getId(), taskId);
        return new Result(ResultStatus.success.getStatus(), "选课成功");
    }
}
